package cn.com.shopec.erp.product.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.com.shopec.erp.common.constant.SZSCMConstant;
import cn.com.shopec.erp.common.utils.LogicUtil;
import cn.com.shopec.erp.common.utils.StringUtil;
import cn.com.shopec.erp.product.dao.ICatBrandDao;
import cn.com.shopec.erp.product.entity.CatBrand;
import cn.com.shopec.erp.product.service.IBrandService;
import cn.com.shopec.erp.product.service.ICatBrandService;
import cn.com.shopec.erp.product.vo.BrandVo;

/**
 * @ClassName: CatBrandServiceImpl
 * @Description: 商品分类与品牌关系接口实现
 * @author: gaoyaxiong
 * @date: 2013-5-30 下午14:14:13
 */
@Service
public class CatBrandServiceImpl implements ICatBrandService {
	
	
	@Resource
	private ICatBrandDao catBrandDao;
	
	@Resource
	private IBrandService brandService;
	
	
	@Override
	public String AddCatBrand(CatBrand cb) {
		try {
			catBrandDao.save(cb);
		} catch (Exception e) {
			e.printStackTrace();
			return SZSCMConstant.FAIL;
		}
		return SZSCMConstant.SUCCESS;
	}

	@Override
	public List<BrandVo> getBrand(String no) {
		List<BrandVo> brandVoList = new ArrayList<BrandVo>();
		if(StringUtil.isExist(no)){
			DetachedCriteria criteria = catBrandDao.createCriteria();
			criteria.add(Restrictions.eq("catNo", no));
			List<CatBrand> list = catBrandDao.findByCriteria(criteria);
			String[] brandNo = new String[list.size()]; 
			int i = 0;
			if(list.size() > 0){
				for (CatBrand cb : list) {
					brandNo[i] = cb.getBrandNo();
					i++;
				}
				brandVoList = brandService.getBrandListByNo(brandNo);
			}
		}
		return brandVoList;
	}

	@Override
	@Transactional
	public String delectCatBrand(CatBrand cb) throws Exception {
		if(LogicUtil.isNotNull(cb)){
			if(StringUtil.isExist(cb.getCatNo())){
				catBrandDao.delectCatBrandByCatNo(cb.getCatNo());
				return SZSCMConstant.SUCCESS;
			}
			if(StringUtil.isExist(cb.getBrandNo())){
				catBrandDao.delectCatBrandByBrandNo(cb.getBrandNo());
				return SZSCMConstant.SUCCESS;
			}
		}
		return SZSCMConstant.FAIL;
		
	}
	
	@Override
	public List<CatBrand> getCatBrandByBrandNo(CatBrand cb){
		DetachedCriteria criteria = this.catBrandDao.createCriteria();
		if(LogicUtil.isNotNull(cb)){
			if(StringUtil.isExist(cb.getBrandNo())){
				criteria.add(Restrictions.eq("brandNo", cb.getBrandNo()));
			}
			if(StringUtil.isExist(cb.getCatNo())){
				criteria.add(Restrictions.eq("catNo", cb.getCatNo()));
			}
			return this.catBrandDao.findByCriteria(criteria);
		}
		return null;
	}
}
